﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Internal;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CADDemo2025
{
    public class Command0226
    {
        [CommandMethod("Demo0226")]
        public void Demo0226()
        {
            if (!UmUserMethod.SelectEntities(out List<Polyline> pls)) return;
            if (!UmUserMethod.GetDouble(out double d, "输入误差", 0)) return;
            List<List<Polyline>> plss = EmEntityMethod.GroupEntities(pls, (c1, c2) => c1.IsConnected(c2, d));
            foreach (var item in plss)
            {
                if (item.Count == 1) continue;
                List<Polyline> clPls = new List<Polyline>();
                foreach (var itme1 in item)
                {
                    clPls.Add(itme1.Clone() as Polyline);
                }
                Polyline pl = clPls.Find(p => clPls.Count(p2 => p != p2 && p.IsConnected(p2, d)) == 1);
                if (pl == null) pl = clPls.First();
                clPls.Remove(pl);
                while (clPls.Count > 0)
                {
                    Line line = new Line();
                    Polyline nextPl = clPls.Find(p => p.IsConnected(pl, d, out line));
                    if (line.Length > 0) pl.JoinEntity(line);
                    pl.JoinEntity(nextPl);
                    clPls.Remove(nextPl);
                }
                pl.AddEntity();
            }
        }
    }
}
